<?php

namespace App\Http\Controllers\Admin\Config;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;

use App\Models\Config;

class ConfigController extends AdminController
{

     /**
     * 获取列表数据
     * @return [type] [description]
     */
    function getLists(Request $request){
        $pageIndex = (int)$request->input('page') ?  $request->input('page') : 1;
        $length    = (int)$request->input('length') ?  $request->input('length') : 10;
        $start     = ($pageIndex-1)*$length;

        $where = [];
        $key = $request->input('key');
        $configModel = Config::where($where);
        if($key){
            $configModel = $configModel->where('key', 'like', "%$key%");
        }

        $data['total'] = $configModel->count();
        if($data['total']>0){
            $data['result'] = $configModel->orderBy('updated_at','desc')->orderBy('key','desc')->skip($start)->take($length)->get()->toArray();
        }
        $this->ajaxJson(0,'',$data);
    }

     /**
     * 获取单条数据
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    function getOne($id){
        $config = $this->_get_one($id);
        $this->ajaxJson(0,'',$config);
    }

    /**
     * 获取某个key所有值
     * @return [type] [description]
     */
    function getkey(Request $request){
        $where = ['key'=>$request->input('key')];
        $this->ajaxJson(0,'',Config::where($where)->orderBy('created_at','desc')->get()->toArray());
    }

    /**
     * 更新配置
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    function updateConfig(Request $request){
    	$data = $request->all();
    	$config = new Config();
        if($data['id']){
            $config = $this->_get_one($data['id']);
        }
        $config->key    = $data['key'];
        $config->vue    = $data['vue'];
        $config->switch = $data['switch']=='true' ? 1 : 0;
        $config->status = $data['status'];
        $config->type   = $data['type'];
        $config->desc   = $data['desc'];
        $config->cacheEmpty($config->key)->save();
    	$this->ajaxJson(0,'更新成功');
    }

    /**
     * 删除某条配置
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    function deleteOne($id){
        $config = $this->_get_one($id);
        $config->cacheEmpty($config->key)->delete();
        $this->ajaxJson(0,'删除成功');
    }

    /**
     * 公共获取单条数据
     * @return [type] [description]
     */
    private function _get_one($id){
        $config = Config::find($id);
        if(!$config){
            $this->ajaxJson(1,'数据不存在,请刷新页面');
        }
        return $config;
    }
}
